package com.cocos.game;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.cocos.lib.CocosHelper;
import com.cocos.lib.CocosJavascriptJavaBridge;
import com.cocos.lib.JsbBridgeWrapper;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;



import java.util.HashMap;
import java.util.Map;


public class GoogleUtils {
    private String  m_actTag ="GoogleUtils";
    private String  m_googleLoginCallBackFuncTS="";
    private String client_id = "";
    private Activity m_activity=null;
    private static final int SIGN_LOGIN = 901;
    private GoogleSignInClient mGoogleSignInClient;
    private static GoogleUtils g_Instace = null;

    public static GoogleUtils getInstance() {
        if (null == g_Instace) {
            g_Instace = new GoogleUtils();
        }
        return g_Instace;
    }

    public Intent getGoogleIntent() {
        Intent signInInten;
        signInInten = mGoogleSignInClient.getSignInIntent();
        return signInInten;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(mGoogleSignInClient != null) {
            switch (requestCode) {
                case SIGN_LOGIN:
                    Log.d(m_actTag,"setActivityResultGoogle");
                    Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
                    if (task == null) {
                        Log.d(m_actTag,"task：null");
                    }
                    try {
                        GoogleSignInAccount account = task.getResult(ApiException.class);
                        Log.d(m_actTag,"Id:" + account.getId() + "|Email:" + account.getEmail() + "|IdToken:" + account.getIdToken());
                        String personName = account.getDisplayName();
                        String personGivenName = account.getGivenName();
                        String personFamilyName = account.getFamilyName();
                        String personEmail = account.getEmail();
                        String personId = account.getId();
                        String token = account.getIdToken();
                        Uri personPhoto = account.getPhotoUrl();

                        Map<String,String> map = new HashMap<String, String>();
                        map.put("result", "22");
                        map.put("info", "google info success");
                        map.put("id", personId);
                        map.put("token", token);
                        map.put("Email", personEmail);
                        map.put("firstName", personGivenName);
                        map.put("lastName", personFamilyName);
                        map.put("userName", personName);

                        Log.d(m_actTag,"google：SIGN_LOGIN: " + map.toString());

                        JsbBridgeWrapper.getInstance().dispatchEventToScript("onGoogleLoginInCallBack", map.toString());

//                        CocosHelper.runOnGameThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                CocosJavascriptJavaBridge.evalString("cc.log(\"Javascript Java bridge!\")");
//
//                                CocosJavascriptJavaBridge.evalString("window.NativeAPI.callByNative('test',1,true)");
//                            }
//                        });

                    } catch (ApiException e) {
                        e.printStackTrace();
                        Log.d(m_actTag,"ApiException:" + e.getMessage());
                        Log.e(m_actTag, "google login error:" + e.getMessage());
                        Map<String,String> map = new HashMap<String, String>();
                        map.put("result", "21");
                        map.put("info", e.getMessage());
                        Log.d(m_actTag,"error!!!!!");

                        JsbBridgeWrapper.getInstance().dispatchEventToScript("onGoogleLoginInCallBack", map.toString());
                    }
                    break;
            }
        }
    }

    public static void loginGoogle(final String callback){
        GoogleUtils.getInstance().m_googleLoginCallBackFuncTS = callback;
        GoogleUtils.getInstance().m_activity.startActivityForResult(getGoogleIntent(), SIGN_LOGIN);
    }

    public static void logOutGoogle() {
        if(GoogleUtils.getInstance().mGoogleSignInClient != null) {
            GoogleUtils.getInstance().mGoogleSignInClient.signOut();
        }
    }

    public void initSDK(final Activity activity){
        m_activity = activity;
       // client_id = activity.getResources().getString(R.string.google_client_id);
        if (mGoogleSignInClient == null) {
            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions
                    .DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestIdToken(client_id)
                    .build();
            mGoogleSignInClient = GoogleSignIn.getClient(m_activity, gso);
        }

        JsbBridgeWrapper jbw = JsbBridgeWrapper.getInstance();
        jbw.addScriptEventListener("onGoogleLoginIn", arg ->{
            System.out.print("@JAVA: here is the argument transport in" + arg);

            m_activity.startActivityForResult(getGoogleIntent(), SIGN_LOGIN);
//            JsbBridgeWrapper.getInstance().dispatchEventToScript("changeLabelContent","Charlotte");
        });

    }
}
